﻿namespace MicroCloud.EventBuses
{
    /// <summary>
    /// 依赖注入事件处理器实例获取方式
    /// </summary>
    internal class IocEventHandlerFactory : IEventHandlerFactory
    {
        //字段
        private readonly ILogger _logger;
        private readonly IHybridServiceScopeFactory _serviceScopeFactory;
        private readonly Type _handlerType;

        /// <summary>
        /// 初始化一个依赖注入事件处理器实例获取方式 <see cref="IocEventHandlerFactory"/> 的新实例
        /// </summary>
        /// <param name="provider">服务提供者</param>
        /// <param name="handlerType">事件处理器类型</param>
        public IocEventHandlerFactory(IServiceProvider provider, Type handlerType)
        {
            _logger = provider.GetLogger<IocEventHandlerFactory>();
            _serviceScopeFactory = provider.GetService<IHybridServiceScopeFactory>();
            _handlerType = handlerType;
        }

        /// <summary>
        /// 获取事件处理器实例
        /// </summary>
        /// <returns></returns>
        public EventHandlerDisposeWrapper GetHandler()
        {
            IServiceScope scope = _serviceScopeFactory.CreateScope();
            string token = scope.GetHashCode().ToString();
            IServiceProvider scopeProvider = scope.ServiceProvider;
            IEventHandler eventHandler = (IEventHandler)scopeProvider.GetService(_handlerType);
            _logger.LogDebug("创建事件处理器 {handlerType} 的执行作用域，作用域标识 {token}。", _handlerType, token);
            return new EventHandlerDisposeWrapper(eventHandler, () =>
            {
                scope.Dispose();
                _logger.LogDebug("释放事件处理器 {handlerType} 的执行作用域，作用域标识 {token}。", _handlerType, token);
            });
        }

    }

}
